using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ChangeEquipsController : MonoBehaviour
{
    [SerializeField] private Button hat01Button;
    [SerializeField] private Button hat02Button;
    [SerializeField] private Button hat03Button;
    [SerializeField] private SkinnedMeshRenderer characterSkinnedMesh;
    [SerializeField] private Transform hatSlot;
    [SerializeField] private GameObject character;

    void Start()
    {
        hat01Button.onClick.AddListener(() => { ChangeEquips("hat01"); });
        hat02Button.onClick.AddListener(() => { ChangeEquips("hat02"); });
        hat03Button.onClick.AddListener(() => { ChangeEquips("hat03"); });
    }

    void Update()
    {
        character.GetComponent<Animation>().Play("act");
    }

    private void ChangeEquips(String equipName)
    {
        if (hatSlot.childCount > 0)
        {
            Destroy(hatSlot.GetChild(0).gameObject);
        }

        SkinnedMeshRenderer equipSkinnedMesh = Instantiate(
            Resources.Load<GameObject>($"Equips/{equipName}"),
            hatSlot
        ).GetComponentInChildren<SkinnedMeshRenderer>();
        equipSkinnedMesh.bones = GetNewBones(characterSkinnedMesh, equipSkinnedMesh);
    }
    
    private Transform[] GetNewBones(SkinnedMeshRenderer root, SkinnedMeshRenderer equip)
    {
        List<Transform> newBones = new List<Transform>();
        foreach(var rb in root.bones)
        {
            foreach(var eb in equip.bones)
            {
                if (rb.name == eb.name)
                {
                    newBones.Add(rb);
                }
            }
        }
        return newBones.ToArray();
    }
}
